package com.aispeech.detector.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class FileUtils {

    public static File getExternalDirectory() {
        Log.i("Utils", "getExternalStorageDirectory=" + Environment.getExternalStorageDirectory());
        File dir = new File(Environment.getExternalStorageDirectory(), "aispeech");
        if (!dir.exists()) {
            dir.mkdirs();
        }

        if (dir.exists()) {
            return dir;
        } else {
            return null;
        }
    }

    public static String sdcardPcmFilePath(Context context, String recordInfo) {
        String filePath;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String fileName = dateFormat.format(new Date(System.currentTimeMillis())) + "_" + recordInfo + ".pcm";
        if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
            filePath = new File(getExternalDirectory(), fileName).getPath();
        } else {
            filePath = new File(context.getExternalCacheDir(), fileName).getPath();
        }

        return filePath;
    }

    /**
     * 获取路径下的所有文件/文件夹
     *
     * @param directoryPath  需要遍历的文件夹路径
     * @param isAddDirectory 是否将子文件夹的路径也添加到list集合中
     */
    public static ArrayList<String> getAllFile(String directoryPath, boolean isAddDirectory) {
        ArrayList<String> list = new ArrayList<String>();
        File baseFile = new File(directoryPath);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if (isAddDirectory) {
                    list.add(file.getAbsolutePath());
                }
                list.addAll(getAllFile(file.getAbsolutePath(), isAddDirectory));
            } else {
                list.add(file.getAbsolutePath());
            }
        }
        return list;
    }

}
